

package com.api.controller;



import cn.hutool.crypto.digest.DigestUtil;
import com.api.annotation.Login;
import com.api.annotation.LoginUser;
import com.api.common.constant.Constant;
import com.api.common.exception.MySystemException;
import com.api.common.page.PageData;
import com.api.common.utils.ConvertUtils;
import com.api.common.utils.Result;
import com.api.entity.Item;
import com.api.entity.User;
import com.api.entity.dto.ItemDTO;
import com.api.entity.dto.LoginDTO;
import com.api.entity.dto.RegisterDTO;
import com.api.entity.dto.UserDTO;
import com.api.service.TokenService;
import com.api.service.UploadService;
import com.api.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

/**
 * 登录接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api/user")
@Tag(name = "登录接口")
@AllArgsConstructor
public class UserController {
    private final UserService userService;
    private final TokenService tokenService;

    @Autowired
    private UploadService uploadService;
    /**
     * 分页
     */
    @Login
    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "province", description = "角色名", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "name", description = "岗位", in = ParameterIn.QUERY, ref = "String")
    })
    public Result<PageData<UserDTO>> page(@RequestParam Map<String, Object> params){
        PageData<UserDTO> page = userService.page(params);

        ArrayList<UserDTO> res = new ArrayList<>();
        for (UserDTO userDTO : page.getList()) {
            userDTO.setProfile(uploadService.toAbsoluteUrl(userDTO.getProfile()));
            res.add(userDTO);
        }
        page.setList(res);

        return new Result<PageData<UserDTO>>().ok(page);
    }
    @Login
    @PostMapping
    @Operation(summary = "保存")
    public Result save(@RequestBody UserDTO dto) {
        dto.setProfile(uploadService.deleteFile(dto.getProfile()));
        User item = ConvertUtils.sourceToTarget(dto, User.class);
        item.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
        userService.insert(item);
        return new Result();
    }
    @Login
    @PutMapping("update")
    @Operation(summary = "修改")
    public Result update(@RequestBody UserDTO dto) {
        dto.setProfile(uploadService.deleteFile(dto.getProfile()));
        User item = ConvertUtils.sourceToTarget(dto, User.class);
        item.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
        userService.updateById(item);
        return new Result();
    }

    @Login
    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    public Result delete(@PathVariable("id") Long id) {
        userService.deleteById(id);
        return new Result();
    }

    @PostMapping("register")
    @Operation(summary = "注册")
    public Result register(@RequestBody RegisterDTO dto) {
        User user = new User();
        dto.setProfile(uploadService.deleteFile(dto.getProfile()));
        user.setUserName(dto.getUsername());
        user.setNickName(dto.getNickName());
        user.setProfile(dto.getProfile());
        user.setSalary(dto.getSalary());
        user.setUniversity(dto.getUniversity());
        user.setPost(dto.getPost());
        user.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
        LambdaQueryWrapper<User> lwq = new LambdaQueryWrapper<>();
        lwq.eq(User::getUserName,dto.getUsername());
        if (userService.exists(lwq)){
            throw new MySystemException("用户名已经存在");
        }
        userService.insert(user);
        return new Result();
    }

    @PostMapping("login")
    @Operation(summary = "登录")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {
        //用户登录
        Map<String, Object> map = userService.login(dto);
        return new Result().ok(map);
    }

    @PostMapping("isRegister")
    @Operation(summary = "查看是否注册")
    public Result<Double> isRegister(@RequestBody LoginDTO dto) {
        LambdaQueryWrapper<User> lwq = new LambdaQueryWrapper<>();
        lwq.eq(User::getUserName,dto.getUsername());
        if (userService.exists(lwq)){
            throw new MySystemException("账户已经存在");
        }
        return new Result().ok(true);
    }

    @PostMapping("update")
    @Operation(summary = "修改信息")
    public Result update(@RequestBody User dto) {
        dto.setProfile(uploadService.deleteFile(dto.getProfile()));
        //查询是否存在
        if (StringUtils.isNotBlank(dto.getPassword())){
            dto.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
        }

        User user = new User();
        BeanUtils.copyProperties(dto, user);
        userService.updateById(user);
        return new Result();
    }



    @Login
    @GetMapping("userInfo")
    @Operation(summary = "获取用户信息")
    public Result<User> userInfo(@Parameter(hidden = true) @LoginUser User user) {
        user.setProfile(uploadService.toAbsoluteUrl(user.getProfile()));
        return new Result<User>().ok(user);
    }

    @Login
    @GetMapping("userId")
    @Operation(summary = "获取用户ID")
    public Result<Long> userInfo(@Parameter(hidden = true) @RequestAttribute("userId") Long userId) {
        return new Result<Long>().ok(userId);
    }

    @Login
    @PostMapping("logout")
    @Operation(summary = "退出")
    public Result logout(@Parameter(hidden = true) @RequestAttribute("userId") Integer userId) {
        tokenService.expireToken(userId);
        return new Result();
    }
}
